<!-- 见证pdf组件 -->
<template>
  <div class="witnessPdf">
    <div v-if="loadingFlag" class="loading-box">
      <!-- {{ src }} -->
      <div class="center-box">
        <img src="@/assets/imgs/loading.gif" alt="" srcset="" />
        <div class="loading-msg">加载中，请稍后…</div>
        <el-progress :percentage="percentage" :color="customColor"></el-progress>
      </div>
    </div>
    <template v-else>
      <div v-if="show" class="pdf-btns">
        <!-- 当附件id为空时，禁用按钮 -->
        <el-button type="primary" plain class="ui-pl10" :disabled="!src" @click="$refs.pdfPrint.print()">
          打印
        </el-button>
        <el-button type="primary" :disabled="!downLoadSrc" @click="pdfDownloadFn()">保存</el-button>
      </div>
      <div v-if="show" class="pdf-box" :style="'height:' + pdfBoxHeight">
        <!-- pdf展示区 -->
        <div v-for="i in pdfTotalPages" :key="i" class="pdf_num_div">
          <pdf :key="i" :src="src" :page="i" style="display: inline-block; width: 100%" />
          <!-- 暂时没有显示页码的需求 -->
          <!-- <span class="pageNume">{{i}}/{{pdfTotalPages}}</span> -->
        </div>
        <!-- 生成一个不可见的pdf,主要用于打印 -->
        <pdf ref="pdfPrint" style="display: none" :src="src" />
      </div>
    </template>
  </div>
</template>
<script>
  // 这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
  // attachmentList, attachDownload
  import { witnessRecordReport } from "../api/api";
  import pdf from "vue-pdf-cs";
  import CMapReaderFactory from "vue-pdf/src/CMapReaderFactory.js";
  export default {
    // 引入组件
    components: { pdf },
    props: {
      // 显示pdf信息
      show: {
        type: Boolean,
        default: false
      },
      // 获取附件相关信息的参数
      pdfParamsBaogao: {
        type: Object,
        default: () => ({
          belongId: "", // 附件归属主键id——必传参数
          attachTypeCode: "" // 附件编码——必传参数
        })
      },
      // pdf盒子高度
      pdfBoxHeight: {
        type: String,
        default: "100%"
      }
    },
    data() {
      // 这里存放数据
      return {
        loadingFlag: false,
        percentage: 20,
        customColor: "#1890FF",
        src: "", // 附件预览和打印链接
        pdfTotalPages: 0, // pdf总页码
        downLoadSrc: "" // 下载的url
      };
    },
    // 监听属性 类似于data概念
    computed: {},
    // 监控data中的数据变化
    watch: {
      show: {
        immediate: true, // true首次加载执行，否则不执行为false或不添加此属性
        handler: function (val) {
          if (val) {
            this.witnessRecordReportFn();
          }
        }
      }
    },
    // 生命周期 - 创建完成（可以访问当前this实例）
    created() {
      console.log("localStorage", localStorage);
      this.percentage = +localStorage.getItem(this.pdfParamsBaogao.belongId) || 0;
    },
    // 生命周期 - 挂载完成（可以访问DOM元素）
    mounted() {
      console.log(this.pdfParamsBaogao, "==============1111");
    },
    // 生命周期 - 销毁之前
    beforeDestroy() {
      console.log("销毁");
      clearTimeout(this.timeListFlag);
      clearTimeout(this.timeFlag);
    },
    // 生命周期 - 销毁完成
    destroyed() {},
    // 如果页面有keep-alive缓存功能，这个函数会触发
    activated() {},
    // 方法集合
    methods: {
      // 获取附件信息
      async witnessRecordReportFn(flag) {
        clearTimeout(this.timeListFlag);
        clearTimeout(this.timeFlag);
        console.log("flag", flag);
        try {
          this.src = "";
          this.pdfTotalPages = 0;
          this.downLoadSrc = "";
          const res = await witnessRecordReport(this.pdfParamsBaogao);
          console.log("res", res.success);
          console.log("res", res.code);
          if (res.success) {
            // 1、进度条20/40/60、80、100；间隔2秒，停留到80，等待接口返回，1秒到100；
            // 2、单人切换页面，从当前进度开始
            // 3、多人点同一个，都从0开始，各走各的；
            // 4、2秒调一次接口：a.返回pdf；b.返回生成中；
            // 如果 生成中。。。
            if (res.code === 20219 || process.env.NODE_ENV === "1development") {
              this.loadingFlag = true;
              this.percentage = +localStorage.getItem(this.pdfParamsBaogao.belongId) || 0;
              console.log("11");
              console.log(" this.percentage", this.percentage + 1);
              // 进度条
              this.increase();
              // 轮询直到完成
              this.timeListFlag = setTimeout(() => {
                this.witnessRecordReportFn();
              }, 2000);
              // if (!flag || process.env.NODE_ENV !== "1development") {
              //   return;
              // }
            }
            // 生成完成
            if (res.code === 0) {
              console.log("this.", "over");
              this.percentage = 100;
              clearTimeout(this.timeListFlag);
              clearTimeout(this.timeFlag);
              // 让进度条走完
              setTimeout(() => {
                this.loadingFlag = false;
                this.percentage = 0;
              }, 1000);
              localStorage.removeItem(this.pdfParamsBaogao.belongId); // 清除记录进度条
              // if (res.data.length) {
              // }
              // 生成下载链接
              this.downLoadSrc = `${process.env.VUE_APP_API}/platform/attach/download?attachId=${res.data[0].attachId}`;
              console.log('this.downLoadSrc', this.downLoadSrc);

              // 生成预览和打印链接
              this.src = pdf.createLoadingTask({
                url: this.downLoadSrc,
                CMapReaderFactory
              });
              this.src.then((pdf1) => {
                console.log("pdf1===", pdf1);
                this.pdfTotalPages = pdf1.numPages;
              });
            }
          } else {
            this.$message({
              type: "error",
              message: res.message ? res.message : "pdf文件暂未获取，请稍后再试",
              single: true
            });
          }
        } catch (error) {
          console.error(error);
          this.$message({
            type: "error",
            message: "pdf文件暂未获取，请稍后再试！",
            single: true
          });
        }
      },
      // 下载
      pdfDownloadFn() {
        window.location.href = this.downLoadSrc;
      },
      // 进度条增加
      increase() {
        console.log(" this.percentage", this.percentage);
        clearTimeout(this.timeFlag);
        this.percentage += 20; // Math.floor((((Math.random() + 9.5) * 10) / 100) * 20);
        if (this.percentage >= 80) {
          this.percentage = 80;
          clearTimeout(this.timeFlag);
        }
        localStorage.setItem(this.pdfParamsBaogao.belongId, this.percentage);
        // this.timeFlag = setTimeout(() => {
        //   this.increase();
        // }, 2000);
        // console.log("this.percentage", this.percentage);
      }
    }
  };
</script>
<style lang="scss" scoped>
  .witnessPdf {
    width: 100%;
    height: 100%;
    margin-top: 50px;
    .loading-box {
      flex-grow: 1;
      display: flex;
      flex-direction: row; /* 子元素横向排列 */
      justify-content: center; /* 相对父元素水平居中 */
      align-items: center;
      height: 100%;
      .center-box {
        width: 400px;
        height: 400px;
        text-align: center;
        img {
          width: 234px;
        }
        .loading-msg {
          margin-top: -10px;
          margin-bottom: 10px;
          font-size: 16px;
        }
      }
    }
    .pdf-btns {
      position: absolute;
      right: 0px;
      bottom: 0px;
      background: #fff;
      width: 100%;
      text-align: right;
      padding: 10px;
    }
    .pdf-box {
      width: 100%;
      height: 100%;
      box-sizing: border-box;
      // padding: 30px;
      padding-left: 25%;
      padding-right: 25%;
      // padding-bottom: 0;
      background: #eee;
      border-radius: 0px 0px 2px 2px;
      overflow: auto;
      .pdf_num_div {
        // margin-bottom: 10px;
        position: relative;
        overflow: hidden;
        .pageNume {
          font-size: 12px;
          color: #666;
          position: absolute;
          bottom: 10px;
          left: calc(50% - 10px);
        }
      }
    }
  }
</style>
